<?php
class BookController
{
    private $bookModel;

    public function __construct($db)
    {
        $this->bookModel = new BookModel($db);
    }

    public function index($page = 1)
    {
        $booksPerPage = 10;
        $offset = max(0, ($page - 1) * $booksPerPage);
        $books = $this->bookModel->getBooksWithPagination($booksPerPage, $offset);
        $totalBooks = $this->bookModel->getTotalBooks();
        $totalPages = ceil($totalBooks / $booksPerPage);
        require 'views/Book_list.php';
    }

    public function create()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = htmlspecialchars($_POST['title']);
            $author = htmlspecialchars($_POST['author']);
            $isbn = htmlspecialchars($_POST['isbn']);
            $publishedDate = htmlspecialchars($_POST['publishedDate']);

            try {
                $this->bookModel->addBook($title, $author, $isbn, $publishedDate);
                header('Location: index.php');
                exit;
            } catch (Exception $e) {
                // 记录错误日志
                error_log($e->getMessage());
                // 显示错误信息给用户
                echo "添加书籍失败，请稍后再试。";
            }
        } else {
            require 'views/add_book.php';
        }
    }

    public function edit($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $title = htmlspecialchars($_POST['title']);
            $author = htmlspecialchars($_POST['author']);
            $isbn = htmlspecialchars($_POST['isbn']);
            $publishedDate = htmlspecialchars($_POST['publishedDate']);

            try {
                $this->bookModel->updateBook($id, $title, $author, $isbn, $publishedDate);
                header('Location: index.php');
                exit;
            } catch (Exception $e) {
                // 记录错误日志
                error_log($e->getMessage());
                // 显示错误信息给用户
                echo "更新书籍失败，请稍后再试。";
            }
        } else {
            $book = $this->bookModel->getBookById($id);
            require 'views/edit_book.php';
        }
    }

    public function delete($id)
    {
        try {
            $this->bookModel->deleteBook($id);
            header('Location: index.php');
            exit;
        } catch (Exception $e) {
            // 记录错误日志
            error_log($e->getMessage());
            // 显示错误信息给用户
            echo "删除书籍失败，请稍后再试。";
        }
    }
}
